from PySide6.QtWidgets import QDialog,QMessageBox
from sqlalchemy.orm import Session
from PySide6.QtCore import QStringListModel
from settings.publicvar import engine
from views.issuedmange.sureissuedperson.savepersondata import Ui_savepersondata

class SavePersonDataView(QDialog,Ui_savepersondata):
    def __init__(self,data):
        super().__init__()
        self.setupUi(self)
        self.data = data
        self.autoLoadData()

        self.cancelbtn.clicked.connect(self.close)
        self.savedialogbtn.clicked.connect(self.savedialogFun)

    # 加载数据
    def autoLoadData(self):
        names = [item.name for item in self.data]
        namemodel = QStringListModel()
        namemodel.setStringList(names)
        self.personlist.setModel(namemodel)
        self.showtotalperson.setText('共%s人要保存，请确认!'%len(self.data))

    # 保存数据
    def savedialogFun(self,):
        purpose = self.purpose.text().strip()
        if not purpose:
            QMessageBox.critical(None,'提示','必需输入用途，不然不可以保存数据')
        else:
            issuedpersonsure = []
            for item in self.data:
                item.purpose = purpose
                issuedpersonsure.append(item)
            with Session(engine) as session,session.begin():
                session.add_all(issuedpersonsure)
                QMessageBox.information(None, '成功',
                                        '添加成功%s条！,请到打印数据处，下载数据！' % len(issuedpersonsure))
                self.close()